//
//  MapAndLocation.m
//  定位demo
//
//  Created by lanou3g on 15/7/24.
//  Copyright (c) 2015年 何炜. All rights reserved.
//

#import "MapAndLocation.h"
#import "LORequestManger.h"
#define kOneUrl @"http://api.k780.com:88/?app=weather.today&weaid="
#define kTwoUrl @"&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json"
@implementation MapAndLocation
static MapAndLocation *location;
+ (MapAndLocation *)shareLocation
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        location = [[MapAndLocation alloc]init];
        location.dataDic=[[NSMutableDictionary alloc] init];
        
    });
    return location;
}
- (CLGeocoder *)geocoder
{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc]init];
    }
    return _geocoder;
}

- (void)starLocationNow:(LocationCompletion)complent
{
    self.mgr.delegate = self;
    _complent =complent;
    
    //判断是否是iOS8
    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        NSLog(@"是iOS8");
        // 主动要求用户对我们的程序授权 授权状态改变就会通知代理
        [self.mgr requestAlwaysAuthorization];
    }
    else
    {
        NSLog(@"iOS7");
        [self.mgr startUpdatingLocation];
    }

}
// 授权状态发生改变时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"等待用户授权");
    }
    else if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        NSLog(@"授权成功");
        //开始定位
        [self.mgr startUpdatingLocation];
    }
}
- (CLLocationManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CLLocationManager alloc]init];
    }
    return _mgr;
}
- (void)openThread
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"所在线程<---->%d",[NSThread isMainThread]);
        [self jiexiUrl];
        // 回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"所在线程---->>>%d",[NSThread isMainThread]);
        });
    });
}

- (void)jiexiUrl
{
    if (self.cityString == nil) {
        return;
    }
    NSString *url = [[kOneUrl stringByAppendingString:self.cityString]stringByAppendingString:kTwoUrl];
    NSLog(@"url == %@",url);
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = [response objectForKey:@"result"];
        self.weather = [dic objectForKey:@"weather"];
        self.temp1 = [dic objectForKey:@"temperature_curr"];
        //self.temp2 = [dic objectForKey:@"temp_high"];
        
        [_dataDic setObject:self.weather forKey:@"weather"];
        [_dataDic setObject:self.temp1 forKey:@"temperature_curr"];
        //[_dataDic setObject:self.temp2 forKey:@"temp_high"];
        
        if (_complent) {
            _complent(YES,self.cityString,_dataDic);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
//获取到位置信息之后就会调用(调用频率非常高)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    
    self.latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
    self.longtitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    
    CLLocation *locationsss = [[CLLocation alloc]initWithLatitude:[self.latitude doubleValue] longitude:[self.longtitude doubleValue]];
    [self.mgr stopUpdatingLocation];
    [_dataDic setObject:self.latitude forKey:@"latitude"];
    [_dataDic setObject:self.longtitude forKey:@"longtitude"];
    
    [self.geocoder reverseGeocodeLocation:locationsss completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark *placemark in placemarks) {
            self.addressString = placemark.administrativeArea;
            [_dataDic setObject:self.addressString forKey:@"addressString"];
            self.locationAddress = _addressString;
            [_dataDic setObject:self.locationAddress forKey:@"locationAddress"];
            
        }
        NSLog(@"获取地理位置成功");
      
        self.locationIsYes = @"加载完成";
        [self getCityData];
        [self openThread];
    }];
}

//获取城市数据
- (void)getCityData
{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"cityList" ofType:@"plist"];
    self.cities = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    self.keys = [NSMutableArray array];
    [self.keys addObjectsFromArray:[[self.cities allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    NSMutableArray *array = [NSMutableArray array];
    [array addObjectsFromArray:[[self.cities allValues] sortedArrayUsingSelector:@selector(compare:)]];
    
    NSString *string = [self.locationAddress substringToIndex:self.locationAddress.length - 1];
    self.cityString = [self.cities objectForKey:string];
    NSLog(@"%@",self.cityString);
    
    [_dataDic setObject:self.cityString forKey:@"cityString"];
    
}
@end
